package com.wu.project.admin.component;

import com.wu.project.admin.entity.LogEntity;
import com.wu.project.admin.property.Constants;
import com.wu.project.admin.service.LogService;
import com.wu.project.admin.util.BaseUtil;
import com.wu.project.admin.util.CommonResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 50816
 */
@ControllerAdvice
@ResponseBody
public class ExceptionHandlerAdvice {

    Logger logger = LoggerFactory.getLogger(ExceptionHandlerAdvice.class);

    @Autowired
    LogService logService;

    @ExceptionHandler(Exception.class)
    public JsonResult defaultHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        logger.error("请求URL:{},异常描述:{},", request.getRequestURI(), e.getMessage(), e);
        LogEntity logEntity = new LogEntity();
        logEntity.setType(Constants.EXCEPTION_TYPE);
        logEntity.setName("异常日志");
        logEntity.setInfo("用户请求:" + request.getRequestURI() + ",发生异常:" + e.getMessage() + System.lineSeparator() + BaseUtil.Instance.FormatStackTrace(e));
        logService.saveExceptionLog(logEntity);

        return CommonResultUtil.Instance.error();
    }
}
